package main

import (
	"fmt"
	"github.com/xgdapg/wtk"
	"net/url"
)

var (
	model ModelInterface
	// pageLimit int = 20
	cfg   *Config
	dbCfg *DbConfig
)

func main() {
	// wtk.EnableGzip = false
	wtk.SessionTTL = 60 * 60 * 24
	// wtk.ListenAddr = "unix:/var/run/blogo.sock"
	// wtk.ListenPort = 81

	fmt.Println(wtk.RunMode, wtk.ListenPort)

	dbCfg = &DbConfig{
		DbAddress:  "",
		DbUsername: "root",
		DbPassword: "",
		DbName:     "blogo",
		DbPrefix:   "blogo_",
	}
	wtk.LoadConfig(dbCfg)

	model = new(DefaultModel)
	model.Init()
	defer model.Close()

	cfg = &Config{
		AppPath:    wtk.AppRoot,
		BlogName:   "Yet another blog",
		BlogDesc:   "Webcome!",
		DomainPath: "http://localhost/",
		PrefixPath: "",
		Theme:      "default",
		NumPerPage: 10,
		PwdSecret:  "",
		Password:   "",
	}
	wtk.LoadConfig(cfg)
	LoadSysConfig()
	fmt.Println("Serve at ", cfg.AppPath)

	u, err := url.Parse(cfg.DomainPath)
	fmt.Println(err, u.Path)
	if err == nil && u.Path != "/" {
		fmt.Println(cfg.DomainPath, u.Path)
		wtk.SetPrefixPath(u.Path)
	}

	wtk.AddStaticFileDir("static")
	wtk.AddStaticFileType("ico", "html", "js", "css")

	wtk.AddRoute(`/`, &IndexHandler{})
	wtk.AddRoute(`/{Page(\d+)}`, &IndexHandler{})

	wtk.AddRoute(`/tag/{TagName}`, &TagHandler{})
	wtk.AddRoute(`/tag/{TagName}/{Page(\d+)}`, &TagHandler{})

	wtk.AddRoute(`/post/{PostId(\d+)}`, &PostHandler{})

	wtk.AddRoute(`/admin/login`, &AdminLoginHandler{})
	wtk.AddRoute(`/admin/logout`, &AdminLogoutHandler{})
	wtk.AddRoute(`/admin`, &AdminIndexHandler{})
	wtk.AddRoute(`/admin/index`, &AdminIndexHandler{})
	wtk.AddRoute(`/admin/posts`, &AdminPostsHandler{})
	wtk.AddRoute(`/admin/posts/{Page(\d+)}`, &AdminPostsHandler{})
	wtk.AddRoute(`/admin/posts/tag/{TagName}`, &AdminPostsHandler{})
	wtk.AddRoute(`/admin/posts/tag/{TagName}/{Page(\d+)}`, &AdminPostsHandler{})
	wtk.AddRoute(`/admin/post`, &AdminPostHandler{})
	wtk.AddRoute(`/admin/post/{PostId(\d+)}`, &AdminPostHandler{})
	wtk.AddRoute(`/admin/tags`, &AdminTagsHandler{})
	wtk.AddRoute(`/admin/tag/{TagName}`, &AdminTagHandler{})
	wtk.AddRoute(`/admin/config`, &AdminConfigHandler{})
	wtk.AddRoute(`/admin/plugins`, &AdminPluginsHandler{})
	wtk.AddRoute(`/admin/plugin/{PluginName}`, &AdminPluginHandler{})

	SetTemplateFuncs()

	// wtk.RegisterCustomHttpStatus(404, "404.html")
	// wtk.AddHttpStatusHook(statusCode, hookFunc)

	pluginManager.startPlugins()

	wtk.AddHandlerHook("ReceiveRequest", func(h *wtk.HookHandler) {
		h.Context.SetHeader("X-Powered-By", "Blogo alpha")
	})

	ret := wtk.Run()
	fmt.Println(ret)
}
